import { BASE_URL, TOKEN_KEY, BASE_URL_REMOTE } from '@/utils/config'
import store from '@/store/index.js'
import axios from 'axios'

const service = axios.create({timeout: 40 * 1000 })

service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = uni.getStorageSync(TOKEN_KEY)
    if (token) {
      config.headers['Bearer'] = uni.getStorageSync(TOKEN_KEY)
      config.headers['Authorization'] = `Bearer ${token}`
    }
    // 根据请求自定义字段选择 baseURL 用于走不同的服务器地址
    if (config.isRemote) {
      config.baseURL = BASE_URL_REMOTE
    } else {
      config.baseURL = BASE_URL
    }

    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const { data } = response
    if (data instanceof Blob) {
      // response.data instanceof Blob == true, res maybe bob file
      return data
    }
    if (data.code === 401) {
      // 登录过期
      uni.removeStorageSync(TOKEN_KEY)
      store.commit('REMOVE_TOKEN')
      uni.showToast({ title: '登录过期，请重新登录', icon: 'error' })
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/index'
        })
      }, 500)
      return Promise.reject(data)
    }
    if(data.code !== 200){
      uni.showToast({ title: data.message, icon: 'error' })
      return Promise.reject(data)
    }else{
      return data
    }
  },
  error => {
    console.log('err', error)
    uni.showToast({
      title: '网络异常',
      icon: 'error'
    })
    return Promise.reject(error)
  }
)

export default service

export function uploadRequest(options) {
  const token = uni.getStorageSync(TOKEN_KEY)
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_URL + options.url,
      filePath: options.data, // H5: File | 小程序：path
      name: 'file',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: res => {
        const result = JSON.parse(res.data)
        if (result.code === 200) {
          resolve(result)
        } else {
          uni.showToast({ title: result.message || '上传失败', icon: 'none' })
          reject(result)
        }
      },
      fail: err => {
        console.log('dassaddsad', err)
        uni.showToast({ title: '网络异常', icon: 'none' })
        reject(err)
      }
    })
  })
}